package org.esk.dablog.web.forms;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;
import org.springframework.validation.BindException;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.model.Entry;
import org.esk.dablog.exceptions.ParameterException;
import org.esk.dablog.web.util.RequestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.HashMap;

/**
 * This class
 * User: jc
 * Date: 22.11.2006
 * Time: 12:32:34
 * $Id:$
 */
public class ViewEntryForm extends ParameterizableViewController {

    private EntryManager entryManager;
    private Class commandClass;

    public ViewEntryForm() {
        setCommandClass(Entry.class);
    }


    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        try {
            long entryId = RequestUtils.extractLongParameter(httpServletRequest);
            if (entryId <= 0) {
                throw new ParameterException("invalid entry id");
            }
            Entry e = entryManager.getEntry(commandClass, entryId);
            if (e == null) {
                throw new ParameterException("cannot get entry by id " + entryId);
            }
            Map model = new HashMap();
            model.put("entry", e);
            ModelAndView result = new ModelAndView(getViewName(), model);
            processEntry(httpServletRequest, httpServletResponse, result, e);
            return result;
        } catch (ParameterException ex) {
            logger.error("Error processing form, redirecting...", ex);
            return new ModelAndView(new RedirectView("/", true));
        }
    }

    /**
     * post-process entry
     * @param request
     * @param response
     * @param entry
     */
    protected void processEntry(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView, Entry entry) {
        
    }


    public EntryManager getEntryManager() {
        return entryManager;
    }

    public void setCommandClass(Class commandClass) {
        this.commandClass = commandClass;
    }

    public void setEntryManager(EntryManager entryManager) {
        this.entryManager = entryManager;
    }
}
